package com.qsign.sfrz_android.net;

import android.util.Log;


import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class WebServiceAccessUtils {

    private static final String TAG = "WebServiceAccessUtils";
    private static final String nameSpace = "http://service.commons.hoperun.com/";
    public static String s_OPT_FLAG = "OPT_FLAG";
    public static String s_MSG_INFO = "MSG_INFO";

    /**
     * 调用服务器的方法
     */
    public static String newcall(final String methodName, String param) {
        String url = Settings.getUrl();;
        int timeout = 30000;
        SoapObject request = new SoapObject(nameSpace, methodName);
        if (param != null) {
            request.addProperty("arg0", param);

            Log.d(TAG, "OnWebSercieRequest **** param=" + param);
        }

        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = false;
        envelope.setOutputSoapObject(request);

        final HttpTransportSE ht = new HttpTransportSE(url, timeout);
        ht.debug = true;

        FutureTask<String> future = new FutureTask<>(() -> {
            String OPT_FLAG = "0";
            String MSG_INFO = "";
            try {
                ht.call("\"" + nameSpace + methodName + "\"", envelope);
                if (envelope.getResponse() != null) {
                    OPT_FLAG = "0";
                    MSG_INFO = envelope.getResponse().toString();
                    Log.d(TAG, "OnWebSercieRequest **** MSG_INFO="
                            + MSG_INFO);
                }
            } catch (Exception e) {
                OPT_FLAG = "1";
                MSG_INFO = e.toString();
            }

            String result = "";
            JSONObject retJson = new JSONObject();
            try {
                retJson.put(s_OPT_FLAG, OPT_FLAG);
                retJson.put(s_MSG_INFO, MSG_INFO);
                result = retJson.toString();
            } catch (Exception e) {
                result = "{\"OPT_FLAG\":1,\"MSG_INFO\":\""
                        + e.toString() + "\"}";
            }
            if (OPT_FLAG.equals("1")) {
                Log.d(TAG, "OnWebSercieRequest **** MSG_INFO="
                        + MSG_INFO);
            }
            return result;
        });

        new Thread(future).start();

        try {
            return future.get();
        } catch (InterruptedException | ExecutionException e) {
            return "{\"OPT_FLAG\":1,\"MSG_INFO\":\"" + e.toString() + "\"}";
        }
    }


}
